package com.shopoo.oauth.infrastructure.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopoo.oauth.domain.entity.Menu;
import com.shopoo.oauth.domain.repository.RoleMenuRepository;
import com.shopoo.oauth.infrastructure.database.dataobject.OauthRoleMenuR;
import com.shopoo.oauth.infrastructure.database.mapper.RoleMenuMapper;

import org.springframework.stereotype.Repository;

/**
 * @Description 角色菜单数据仓库实现
 * @Date 2020/12/4 10:38 上午
 * @Author <a href="mailto:android_li@sina.cn">Joe</a>
 **/
@Repository
public class RoleMenuRepositoryImpl extends ServiceImpl<RoleMenuMapper, OauthRoleMenuR> implements RoleMenuRepository {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<String> findAllRoleMenus() {
        List<Menu> menus = roleMenuMapper.findRoleMenus(new LambdaQueryWrapper());
        return menus.stream().map(menu -> {
            return menu.toString();
        }).collect(Collectors.toList());
    }

    @Override
    public void deleteByRoleId(Long roleId) {
        LambdaQueryWrapper<OauthRoleMenuR> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OauthRoleMenuR::getRoleId, roleId);
        this.remove(queryWrapper);
    }

    @Override
    public void saveBatch(Long[] menuIds, Long roleId) {
        if (menuIds == null || menuIds.length == 0) {
            return;
        }
        List<OauthRoleMenuR> list = new ArrayList<>();
        for (int i=0; i<menuIds.length; i++) {
            OauthRoleMenuR oauthRoleMenuR = new OauthRoleMenuR();
            oauthRoleMenuR.setRoleId(roleId);
            oauthRoleMenuR.setMenuId(menuIds[i]);
            list.add(oauthRoleMenuR);
        }
        super.saveBatch(list);
    }
}
